package org.ragdollcat.first.manager.websocket;

import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.ragdollcat.first.constants.SpaceUserPermissionConstant;
import org.ragdollcat.first.exception.ErrorCode;
import org.ragdollcat.first.exception.ThrowUtils;
import org.ragdollcat.first.manager.auth.SpaceUserAuthManager;
import org.ragdollcat.first.model.entity.Picture;
import org.ragdollcat.first.model.entity.Space;
import org.ragdollcat.first.model.entity.User;
import org.ragdollcat.first.model.enums.SpaceTypeEnum;
import org.ragdollcat.first.service.PictureService;
import org.ragdollcat.first.service.SpaceService;
import org.ragdollcat.first.service.UserService;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * websocket请求拦截器
 * 主要是进行权限校验
 */
@Component
@Slf4j
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 进行图片编辑权限校验
     * 将图片信息和用户信息保存到session中
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            Long pictureId = Long.valueOf(servletRequest.getParameter("pictureId"));
            if (ObjUtil.isEmpty(pictureId)) {
                log.error("websocket尝试握手失败，图片信息不存在！");
                return false;
            }
            User loginUser = userService.getLoginUser(servletRequest);
            if (ObjUtil.isEmpty(loginUser)) {
                log.error("websocket尝试握手失败，用户未登录！");
                return false;
            }
            Picture picture = pictureService.getById(pictureId);
            if (ObjUtil.isEmpty(picture)) {
                log.error("websocket尝试握手失败，图片信息为空！");
                return false;
            }
            Long spaceId = picture.getSpaceId();
            Space space = spaceService.getById(spaceId);
            if (ObjUtil.isEmpty(space)) {
                log.error("websocket尝试握手失败，空间信息为空！");
                return false;
            }
            if (space.getSpaceType().equals(SpaceTypeEnum.PRIVATE.getValue())) {
                log.error("websocket尝试握手失败，私有空间不支持该操作！");
                return false;
            }
            //检查图片编辑权限
            List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
            if (!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)) {
                log.error("没有图片编辑权限！");
                return false;
            }

            attributes.put("user", loginUser);
            attributes.put("userId", loginUser.getId());
            attributes.put("pictureId", pictureId);
        }


        return true;
    }

    /**
     * @param request
     * @param response
     * @param wsHandler
     * @param exception
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
